#!/usr/bin/sh

TP2_DAEMON=1
TP2_DAEMON_CONFIG="/var/adm/tp2/tp2daemon.xml"
TP2_LIBS_LIST="/usr/local/tp2/bin /opt/tp2/bin /sas/rcs/bin /appl/smi/develop/tp2/bin"
TP2_RCS_LIST="/usr/local/tp2/tp2.rc /etc/tp2.rc /opt/tp2/tp2.rc /opt/tp2/etc/tp2.rc /sas/rcs/etc/tp2.rc /sas/rcs/etc/tp2 /etc/rc.config.d/tp2"

TP2_LIBS=""
for c in $TP2_LIBS_LIST
do
	if [[ -d $c && -x "$c/tp2daemon" ]]
	then
		TP2_LIBS=$c
		break
	fi
done

TP2_RC=""
for c in $TP2_RCS_LIST
do
	if [ -f $c ]
	then
		TP2_RC=$c
		break
	fi
done

export TP2_DAEMON
export TP2_DAEMON_CONFIG

if [[ x$TP2_RC != x && -r $TP2_RC ]]
then
	. $TP2_RC
fi

if [ x$TP2_DAEMON_CONFIG = x ]
then
	echo "Warning: TP2_DAEMON_CONFIG not set - aborting." >&2
	exit 1
fi

if [ x$1 = x ]
then
	arg=start
else
	arg=$1
fi

if [ $arg = start ]
then
	[ $TP2_DAEMON -eq 0 ] && exit 0
	cd $TP2_LIBS
	./tp2daemon -C $TP2_DAEMON_CONFIG
	exit $?
fi
if [ $arg = stop ]
then
	[ $TP2_DAEMON -eq 0 ] && exit 0
	x=`ps -ef | egrep "perl.*-w.*/tp2daemon" | grep -v grep | awk '{print $2}'`
	[ -n "$x" ] && kill $x
	exit 0
fi

if [ $arg = start_msg ]
then
	echo "Starting TP2 Daemon"
	exit 0
fi

if [ $arg = stop_msg ]
then
	echo "Stopping TP2 Daemon"
	exit 0
fi

echo "usage: $0 { start | stop | start_msg | stop_msg }"
exit 1
